import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

export function useAtomView(showAtom) {
  function initAtom(containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    const renderer = new THREE.WebGLRenderer({
      antialias: true,
      autoClear: true,
    });
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor("rgb(17, 30, 84)", 1);

    const camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      0.01,
      1000
    );
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    camera.position.set(0, 0.9, 0.2);

    const controls = new OrbitControls(camera, renderer.domElement);
    const targetPosition = new THREE.Vector3(0, 0, 0);
    controls.target = targetPosition;
    controls.enableDamping = true;
    controls.enableRotate = true;
    controls.enableZoom = true;
    controls.enablePan = true;
    const scene = new THREE.Scene();

    // 光照
    const light1 = new THREE.DirectionalLight(0xfefaf1, 1);
    light1.position.set(8, 5, 7);
    light1.castShadow = true;
    light1.shadow.camera.near = 1;
    light1.shadow.camera.far = 300;
    light1.shadow.mapSize.width = 2048;
    light1.shadow.mapSize.height = 2048;
    light1.shadow.bias = -0.005;

    const light2 = new THREE.DirectionalLight(0xfefaf1, 1);
    light2.position.set(-8, 5, -7);
    light2.castShadow = true;
    light2.shadow.camera.near = 1;
    light2.shadow.camera.far = 300;
    light2.shadow.mapSize.width = 2048;
    light2.shadow.mapSize.height = 2048;
    light2.shadow.bias = -0.005;

    const mainLight = new THREE.DirectionalLight(0xffffff, 15);
    mainLight.position.set(-4.45, 5, -6.08);
    mainLight.castShadow = true;
    mainLight.shadow.camera.near = 1;
    mainLight.shadow.camera.far = 300;
    mainLight.shadow.mapSize.width = 1024;
    mainLight.shadow.mapSize.height = 1024;
    mainLight.visible = true;

    scene.add(light1, light2, mainLight);

    // 添加网格平面（GridHelper）
    // const gridHelper = new THREE.GridHelper(200, 200, 0x98979f, 0xcccccc);
    // gridHelper.position.y = -0.01; // 避免与地面重合导致 Z-fighting
    // scene.add(gridHelper);

    // 模型加载
    const loader = new GLTFLoader();
    const group = new THREE.Group();
    scene.add(group);

    loader.load("/static/tb0001.glb", (gltf) => {
      gltf.scene.scale.multiplyScalar(0.05);
      gltf.scene.position.set(0, 0, 0);
      group.add(gltf.scene);
      yuanzi = gltf.scene;
      gltf.scene.traverse((obj) => {
        if (obj.isMesh) {
          obj.material = new THREE.MeshLambertMaterial({
            color: "#7cdcf0",
            transparent: true,
            opacity: 0.2,
            depthWrite: false,
          });

          const edges = new THREE.EdgesGeometry(obj.geometry);
          const edgeMat = new THREE.LineBasicMaterial({ color: 0x7cdcf0 });
          const line = new THREE.LineSegments(edges, edgeMat);
          obj.add(line);
        }
        if (obj.name == "Box3169") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3169",
            worldPosition,
            "static/shujuzhongx.png"
          );
        }
        if (obj.name == "Box3180") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3180",
            worldPosition,
            "static/shujuzhongx.png"
          );
        }
        if (obj.name == "Box3205") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3205",
            worldPosition,
            "static/shujuzhongx.png"
          );
        }
        if (obj.name == "Box3216") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3216",
            worldPosition,
            "static/shujuzhongx.png"
          );
        }
        if (obj.name == "Box3170") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(group, "Box3170", worldPosition, "static/fuwuqi.png");
        }
        if (obj.name == "Box3171") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(group, "Box3171", worldPosition, "static/fuwuqi.png");
        }
        if (obj.name == "Box3181") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(group, "Box3181", worldPosition, "static/fuwuqi.png");
        }
        if (obj.name == "Box3182") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(group, "Box3182", worldPosition, "static/fuwuqi.png");
        }
        if (obj.name == "Box3206") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(group, "Box3206", worldPosition, "static/fuwuqi.png");
        }
        if (obj.name == "Box3207") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(group, "Box3207", worldPosition, "static/fuwuqi.png");
        }
        if (obj.name == "Box3217") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(group, "Box3217", worldPosition, "static/fuwuqi.png");
        }
        if (obj.name == "Box3218") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(group, "Box3218", worldPosition, "static/fuwuqi.png");
        }
        if (obj.name == "Box3172") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3172",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3197") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3197",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3174") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3174",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3199") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3199",
            worldPosition,
            "static/kehuduan.png"
          );
        }

        if (obj.name == "Box3176") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3176",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3178") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3178",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3201") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3201",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3203") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3203",
            worldPosition,
            "static/kehuduan.png"
          );
        }

        if (obj.name == "Box3208") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3208",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3210") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3210",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3212") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3212",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3214") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3214",
            worldPosition,
            "static/kehuduan.png"
          );
        }

        if (obj.name == "Box3219") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3219",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3221") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3221",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3223") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3223",
            worldPosition,
            "static/kehuduan.png"
          );
        }
        if (obj.name == "Box3225") {
          const worldPosition = new THREE.Vector3();
          obj.getWorldPosition(worldPosition);
          spiritGenerate(
            group,
            "Box3225",
            worldPosition,
            "static/kehuduan.png"
          );
        }
      });
    });
    function spiritGenerate(parent, name, position, url) {
      const PipelineMaterial = new THREE.SpriteMaterial({
        map: new THREE.TextureLoader().load(url),
        transparent: true,
        opacity: 0.9,
        depthWrite: false,
      });

      const Pipeline1 = new THREE.Sprite(PipelineMaterial);
      Pipeline1.name = name;
      Pipeline1.scale.set(0.11, 0.11, 0.11);
      Pipeline1.position.set(position.x, position.y + 0.08, position.z);

      // 👇 添加自定义数据用于标识该精灵图
      Pipeline1.userData = {
        type: "server",
        name: name,
        ip: "192.168.0.1",
        port: "8080", // 👈 新增端口
        status: "online", // 👈 新增状态
      };

      parent.add(Pipeline1);

      // 👇 绑定点击事件监听器
      addSpriteClickListener(Pipeline1);
    }
    // 点击检测相关变量
    const raycaster = new THREE.Raycaster();
    const mouse = new THREE.Vector2();
    let currentDialog = null;
    function showServerInfoDialog(userData) {
      // 防止重复弹出
      if (document.getElementById("server-info-dialog")) {
        document.getElementById("server-info-dialog").remove();
        currentDialog = null;
      }

      // 创建弹窗容器
      const dialog = document.createElement("div");
      dialog.id = "server-info-dialog";
      dialog.style = `
    position: fixed;
    top: 30%;
    left: 50%;
    border: 1px solid #fff;
    transform: translate(-50%, -50%);
    background: rgba(17, 30, 84, 0.88);
    padding: 20px;
    border-radius: 8px;
    color: white;
    width: 300px;
    box-shadow: 0 0 10px #000;
    z-index: 9999;
    font-family: sans-serif;
  `;
      dialog.innerHTML = `
  <h3 style="margin-top: 0;">服务器信息</h3>
  <label>编号：<input id="dialog-name" type="text" value="${
    userData.name
  }" style="width:100%; margin-bottom: 10px; padding: 5px;"></label>
  <label>IP地址：<input id="dialog-ip" type="text" value="${
    userData.ip
  }" style="width:100%; margin-bottom: 10px; padding: 5px;"></label>
  
  <!-- 👇 新增字段 -->
  <label>端口：<input id="dialog-port" type="text" value="${
    userData.port
  }" style="width:100%; margin-bottom: 10px; padding: 5px;"></label>
  <label>状态：
    <select id="dialog-status" style="width:100%; margin-bottom: 10px; padding: 5px;">
      <option value="online" ${
        userData.status === "online" ? "selected" : ""
      }>在线</option>
      <option value="offline" ${
        userData.status === "offline" ? "selected" : ""
      }>离线</option>
    </select>
  </label>

  <div style="text-align:right;">
    <button id="dialog-cancel" style="margin-right: 10px; padding: 5px 10px;border: 1px solid rgb(255, 255, 255);
  color: #ffffff;border-radius: 10px;background-color:rgba(68, 68, 68, 0);cursor: pointer;">取消</button>
    <button id="dialog-ok" style="padding: 5px 10px;border: 1px solid rgb(255, 255, 255);
  color: #ffffff;border-radius: 10px;background-color:rgba(68, 68, 68, 0);cursor: pointer;">确定</button>
  </div>
`;

      document.body.appendChild(dialog);

      // 确认按钮点击
      document.getElementById("dialog-ok").onclick = (e) => {
        e.stopPropagation(); // 👈 关键点
        const newName = document.getElementById("dialog-name").value.trim();
        const newIp = document.getElementById("dialog-ip").value.trim();
        const newPort = document.getElementById("dialog-port").value.trim();
        const newStatus = document.getElementById("dialog-status").value;

        if (newName && newIp) {
          userData.name = newName;
          userData.ip = newIp;
          userData.port = newPort;
          userData.status = newStatus;
          console.log("更新后的服务器信息:", userData);
        }

        dialog.remove();
      };

      // 取消按钮点击
      document.getElementById("dialog-cancel").onclick = (e) => {
          e.stopPropagation(); // 👈 关键点
        dialog.remove();
      };
      currentDialog = dialog;
    }
    function onMouseClick(event) {
      // 计算鼠标位置归一化坐标 (-1 ~ +1)
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

      raycaster.setFromCamera(mouse, camera);

      const intersects = raycaster.intersectObjects(getAllSprites(), true);

      if (intersects.length > 0) {
        const clickedSprite = intersects[0].object;
        if (
          clickedSprite &&
          clickedSprite.userData &&
          clickedSprite.userData.type === "server"
        ) {
          showServerInfoDialog(clickedSprite.userData); // 调用弹窗函数
        }
      }
    }

    function getAllSprites() {
      const sprites = [];
      group.traverse((obj) => {
        if (obj.isSprite) {
          sprites.push(obj);
        }
      });
      return sprites;
    }

    function addSpriteClickListener(sprite) {
      window.addEventListener("click", onMouseClick);
    }
    // 调整窗口大小监听器
    function onResize() {
      const w = window.innerWidth;
      const h = window.innerHeight;
      camera.aspect = w / h;
      camera.updateProjectionMatrix();
      renderer.setSize(w, h);
    }

    window.addEventListener("resize", onResize);
    container.appendChild(renderer.domElement);
    showAtom.value = false;

    function animate() {
      controls.update();
      requestAnimationFrame(animate);
      if (showAtom.value) {
        renderer.render(scene, camera);
      } else {
        if (currentDialog && currentDialog.parentElement) {
          currentDialog.parentElement.removeChild(currentDialog);
          currentDialog = null;
        }
        if (camera.position.y != 0.9 || camera.position.y != 0.2) {
          camera.position.set(0, 0.9, 0.2);
          targetPosition.x = 0;
          targetPosition.y = 0;
          targetPosition.z = 0;
        }
      }
    }

    animate();

    return () => {
      window.removeEventListener("resize", onResize);
      if (group && group.parent) {
        group.parent.remove(group);
      }
      renderer.dispose();
    };
  }
  let yuanzi;
  function disposeModels(model) {
    model = yuanzi;
    if (!model) return;

    // 从场景中移除
    if (model.parent) {
      model.parent.remove(model);
    }

    // 释放几何体、材质和纹理
    model.traverse((object) => {
      if (object.isMesh) {
        const geometry = object.geometry;
        const material = object.material;

        geometry.dispose();

        if (Array.isArray(material)) {
          material.forEach((mtrl) => {
            if (mtrl.map) mtrl.map.dispose();
            mtrl.dispose();
          });
        } else {
          if (material.map) material.map.dispose();
          material.dispose();
        }
      }
    });

    // 置空引用
    model = null;
  }

  return {
    initAtom,
    disposeModels,
  };
}
